package com.sky.earnmoney.data;

import com.sky.earnmoney.api.CallbackData;
import com.sky.earnmoney.api.HttpResult;
import com.sky.earnmoney.api.NetWorkUtils;
import com.sky.earnmoney.data.model.LoggedInUser;

import java.io.IOException;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class LoginDataSource {

    public Result<LoggedInUser> login(String username, String password) {

        try {

            HashMap<String,Object> map = new HashMap<>();
            map.put("mobile",username);
            map.put("password",password);
            Response<HttpResult<String>> response = NetWorkUtils.getInstance().getApi().checkLogin(map).execute();
            if(response.isSuccessful()){
                String body = response.body().data;
                LoggedInUser fakeUser =
                        new LoggedInUser(
                                java.util.UUID.randomUUID().toString(),
                                "Jane Doe",body);
                return new Result.Success<>(fakeUser);
            }
            return new Result.Error(new Exception(response.message()));
        } catch (Exception e) {
            return new Result.Error(new IOException("Error logging in", e));
        }
    }

    public void logout() {
        // TODO: revoke authentication
    }

    public void login(String username, String password, CallbackData<String> callback) {
        HashMap<String,Object> map = new HashMap<>();
        map.put("mobile",username);
        map.put("password",password);
        NetWorkUtils.getInstance().getApi().checkLogin(map).enqueue(new Callback<HttpResult<String>>() {
            @Override
            public void onResponse(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                if(response.isSuccessful()){
                    if(callback != null){
                        if(response.body().code == 0){
                            callback.success(response.body().data);
                        }else{
                            callback.error(response.body().msg);
                        }
                    }
                }else{
                    if(callback != null){
                        callback.error(response.message());
                    }
                }
            }

            @Override
            public void onFailure(Call<HttpResult<String>> call, Throwable t) {
                if(callback != null){
                    callback.error(t.getMessage());
                }
            }
        });
    }
}